package com.xiaohei.rabbitmq.four;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;
import com.xiaohei.rabbitmq.utils.RabbitmqUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * @author 王希辰
 * @Date: 2022/3/17 20:32
 * 发布确认模式：
 *  使用的时间 比较那种确认方式是最好的
 *  1.单个确认
 *  2.批量确认
 *  3.异步批量确认
 */
public class ConfirmMessage {
    //批量发消息的个数
    public static final int MESSAGE_COUNT=1000;

    public static void main(String[] args) throws Exception {
        //1.单个确认
        //ConfirmMessage.publishMessageIndividually();//发布1000条单独确认消息，耗时591ms
        //2.批量确认
        //ConfirmMessage.publishMassageBatch();//发布1000条批量确认消息，耗时82ms
        //3.异步批量确认
        ConfirmMessage.publishMassageAsync();//发布1000条异步发布确认消息，耗时38ms
    }
    //单个确认
    public static void publishMessageIndividually() throws Exception {
        Channel channel= RabbitmqUtils.getChannel();
        String queueName= UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);
        //开启发布确认
        channel.confirmSelect();
        //开始时间
        long begin = System.currentTimeMillis();
        //批量发消息
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String m=i+"";
            channel.basicPublish("",queueName,null,m.getBytes(StandardCharsets.UTF_8));
            //单个消息就马上进行发布确认
            boolean flag = channel.waitForConfirms();
            if(flag){
                System.out.println("消息发送成功");
            }
        }
        //结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+MESSAGE_COUNT+"条单独确认消息，耗时"+(end-begin)+"ms");
    }

    //批量发布确认
    public static void publishMassageBatch() throws Exception {
        Channel channel= RabbitmqUtils.getChannel();
        String queueName= UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);
        //开启发布确认
        channel.confirmSelect();
        //开始时间
        long begin = System.currentTimeMillis();
        //批量发送消息 批量发布确认
        int batchSize=100;

        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String mseeage=i+"";
            channel.basicPublish("",queueName,null,mseeage.getBytes(StandardCharsets.UTF_8));
            //判断达到100条消息的时候 批量确认一次
            if(i%batchSize==0){
                channel.waitForConfirms();
            }
        }
        //channel.waitForConfirms();
        //结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+MESSAGE_COUNT+"条批量确认消息，耗时"+(end-begin)+"ms");
    }

    //异步确认发布
    public static void publishMassageAsync() throws Exception {
        Channel channel= RabbitmqUtils.getChannel();
        String queueName= UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);
        //开启发布确认
        channel.confirmSelect();

        //线程安全有序的哈希表 适用于发并发的情况下
        //1.轻松的将序号与消息进行关联
        //2.轻松批量删除条目 只要给到序号
        //3.支持高并发（多线程）
        ConcurrentSkipListMap<Long,String> outstandmingConfirms=new ConcurrentSkipListMap<>();

        //开始时间
        long begin = System.currentTimeMillis();

        //消息确认成功，回调函数
        ConfirmCallback ackCallback =(deliveryTag,multiple)->{
            if(multiple){
                //2.删除已经确认的消息 ，剩下的是未确认的消息
                ConcurrentNavigableMap<Long, String> confirmed = outstandmingConfirms.headMap(deliveryTag);
                confirmed.clear();
            }else {
                outstandmingConfirms.remove(deliveryTag);
            }

            System.out.println(deliveryTag+"消息发送成功");
        };
        //消息确认失败，回调函数
        //1.消息的标记
        //2.是否批量确认
        ConfirmCallback nackCallback =(deliveryTag,multiple)->{
            //3.打印一下未确认的消息有哪些
            String message=outstandmingConfirms.get(deliveryTag);
            System.out.println("未确认的消息:"+deliveryTag+"内容为:"+message);
        };

        //准备消息的监听器 监听那些消息成功，哪些消息失败
        //1.监听哪些消息成功了
        //2.监听哪些消息失败了
        channel.addConfirmListener(ackCallback,nackCallback);//异步通知

        //批量发送消息
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String m=i+"";
            channel.basicPublish("",queueName,null,m.getBytes(StandardCharsets.UTF_8));
            //1.此处记录下所有要发送的消息 ，消息的总和
            outstandmingConfirms.put(channel.getNextPublishSeqNo(),m);
        }

        //结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+MESSAGE_COUNT+"条异步发布确认消息，耗时"+(end-begin)+"ms");
    }


}

